<template>
    <div ref="echart1" class="echart"></div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, onMounted, onBeforeUnmount } from "vue"
import * as echarts from 'echarts'

const echart1 = ref<HTMLElement | null>(null)
let myChart: echarts.ECharts | null = null
let resizeObserver: ResizeObserver | null = null

const props = defineProps({
    data: {
        type: Object,
        default: {}
    }
})

// 初始化图表
const initChart = (option: any) => {
    if (!echart1.value) return
    
    // 如果图表已存在，先销毁
    if (myChart) {
        myChart.dispose()
        myChart = null
    }
    
    // 创建新图表
    myChart = echarts.init(echart1.value)
    myChart.setOption(option, true)
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize)
    
    // 添加容器大小变化监听
    if (resizeObserver) {
        resizeObserver.disconnect()
    }
    resizeObserver = new ResizeObserver(handleResize)
    resizeObserver.observe(echart1.value)
}

// 处理大小变化
const handleResize = () => {
    if (myChart) {
        myChart.resize()
    }
}

// 清理监听器
const cleanup = () => {
    if (myChart) {
        myChart.dispose()
        myChart = null
    }
    if (resizeObserver) {
        resizeObserver.disconnect()
        resizeObserver = null
    }
    window.removeEventListener('resize', handleResize)
}

watch(() => props.data, (newData) => {
    if (!echart1.value) return
    
    if (!Object.keys(newData).length) {
        cleanup()
        return
    }
    
    initChart(newData)
})

onMounted(() => {
    // 初始渲染
    if (props.data && Object.keys(props.data).length) {
        initChart(props.data)
    }
})

onBeforeUnmount(() => {
    cleanup()
})
</script>

<style scoped>
.echart {
    width: 100%;
    height: 100%;
}
</style>